#include <iostream>
#include <string>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "Thread.hpp"
#include "InetAddr.hpp"
#include <memory>
#include <functional>
using namespace std;
using namespace ThreadMoudle;

int InitClient()
{
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        cerr << "create client failed" << endl;
        exit(1);
    }
    return sockfd;
}

// 发送消息
void SendMessage(int sockfd, string serverip, uint16_t serverport, const string &name)
{
    // 客户端一般不用绑定套接字，操作系统会在第一次发送消息时自动绑定本机ip和一个随机的port
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = inet_addr(serverip.c_str());
    server.sin_port = htons(serverport);

    while (true)
    {
        string line;
        cout << name << " #: ";
        getline(cin, line);
        ssize_t res = sendto(sockfd, line.c_str(), line.size(), 0, (struct sockaddr *)&server, sizeof(server));
        if (res <= 0)
        {
            break;
        }
    }
}

// 接收消息
void RecvMessage(int sockfd, const string &name)
{

    while (true)
    {
        struct sockaddr_in peer;
        char buff[1024];
        socklen_t len = 0;
        int n = recvfrom(sockfd, buff, sizeof(buff) - 1, 0, (struct sockaddr *)&peer, &len);
        if (n > 0)
        {
            buff[n] = 0;
            cout << buff << endl;
        }
        else
        {
            cerr << "recvfrom error\n"
                 << endl;
            break;
        }
    }
}

int main(int argc, char *argv[])
{

    if (argc != 3)
    {
        cerr << "Usage:" << argv[0] << " local-port" << endl;
        exit(0);
    }
    string ip = argv[1];
    uint16_t port = stoi(argv[2]);
    int sockfd = InitClient();
    // auto ref = std::bind(&RecvMessage, sockfd, placeholders::_1);
    //  auto senf = std::bind(&SendMessage, sockfd, ip, port, placeholders::_1, placeholders::_2, placeholders::_3);
    Thread recver("recver-thread", std::bind(&RecvMessage, sockfd, std::placeholders::_1));
    Thread sender("sender-thread", std::bind(&SendMessage, sockfd, ip, port, std::placeholders::_1));

    recver.Start();
    sender.Start();
    recver.Join();
    sender.Join();

    close(sockfd);
    return 0;
}